use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::category_translations::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub category_id: String,
    pub locale: String,
    pub name: String,
    pub content: String,
    pub meta_title: Option<String>,
    pub meta_description: Option<String>,
    pub meta_keywords: Option<String>,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Category ID must not be empty."))]
    pub category_id: String,
    #[validate(length(min = 2, message = "Locale must be at least 2 characters."))]
    pub locale: String,
    #[validate(length(min = 1, message = "Name must not be empty."))]
    pub name: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            category_id: self.category_id.as_ref().to_owned(),
            locale: self.locale.as_ref().to_owned(),
            name: self.name.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::category_translations::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a category translation by the provided id
    ///
    /// # Errors
    ///
    /// When could not find category translation or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let translation = category_translations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_translations::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        translation.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds category translations by the provided category id
    ///
    /// # Errors
    ///
    /// When could not find category translations or DB query error
    pub async fn find_by_category_id(
        db: &DatabaseConnection,
        category_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let translations = category_translations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_translations::Column::CategoryId, category_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(translations)
    }

    /// finds category translation by the provided category id and locale
    ///
    /// # Errors
    ///
    /// When could not find category translation or DB query error
    pub async fn find_by_category_and_locale(
        db: &DatabaseConnection,
        category_id: &str,
        locale: &str,
    ) -> ModelResult<Self> {
        let translation = category_translations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_translations::Column::CategoryId, category_id)
                    .eq(category_translations::Column::Locale, locale)
                    .build(),
            )
            .one(db)
            .await?;
        translation.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// Asynchronously creates a category translation and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the category translation into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let translation = category_translations::ActiveModel {
            category_id: ActiveValue::set(params.category_id.to_string()),
            locale: ActiveValue::set(params.locale.to_string()),
            name: ActiveValue::set(params.name.to_string()),
            content: ActiveValue::set(params.content.to_string()),
            meta_title: ActiveValue::set(params.meta_title.clone()),
            meta_description: ActiveValue::set(params.meta_description.clone()),
            meta_keywords: ActiveValue::set(params.meta_keywords.clone()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(translation)
    }
}

impl ActiveModel {
    /// Updates the category translation's content
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_content(
        mut self,
        db: &DatabaseConnection,
        content: String,
    ) -> ModelResult<Model> {
        self.content = ActiveValue::set(content);
        Ok(self.update(db).await?)
    }

    /// Updates the category translation's meta information
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_meta(
        mut self,
        db: &DatabaseConnection,
        title: Option<String>,
        description: Option<String>,
        keywords: Option<String>,
    ) -> ModelResult<Model> {
        self.meta_title = ActiveValue::set(title);
        self.meta_description = ActiveValue::set(description);
        self.meta_keywords = ActiveValue::set(keywords);
        Ok(self.update(db).await?)
    }
}
